<?php
/**
 * To C活动控制器
 */
namespace Beerus\Modules\DesignerCompetition2021\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DesignerCompetition2021\toc\ToCActionLog;
use Doraemon\model\DesignerCompetition2021\toc\ToCPrize;
use Doraemon\service\DesignerCompetition2021\ToC;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Doraemon\cache\DesignerCompetition2021\DcToC as cDcToC;

class PrizeController extends Controller {
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content) {
        $page = $request->get('page', 1);
        $pageSize = $request->get('per_page', self::PAGE_SIZE);
        $request = $request->all();
        $condition = [];
        $total = ToCPrize::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = ToCPrize::select('*', $condition);
        $this->formatList($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column('id', 'ID');
                $grid->column('name', '奖项名称')->width(150);
                $grid->column('full_name', '奖项全称')->width(250);
                $grid->column('prize_type', '奖项类别')->display(function () {
                    return ToC::PRIZE_TYPE_TXT[$this->prize_type];
                })->width(100);
                $grid->column('play_prize_img', '转盘奖项图片')->width(140)->display(function () {
//                    if ($this->prize_type == ToC::PRIZE_TYPE_LOSE) {
//                        return '';
//                    }
                    $prizeImgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $this->play_prize_img, ImgUrl::IMAGE_SIZE_SQ_PHONE);
                    return '<a href="' . $prizeImgUrl . '" target="_blank">
                                <img width="100px" height="100px" src="' .$prizeImgUrl . '">
                            </a>';
                });
                $grid->column('win_prize_img', '获奖奖项图片')->width(140)->display(function () {
                    if ($this->prize_type == ToC::PRIZE_TYPE_LOSE) {
                        return '';
                    }
                    $prizeImgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $this->win_prize_img, ImgUrl::IMAGE_SIZE_SQ_PHONE);
                    return '<a href="' . $prizeImgUrl . '" target="_blank">
                                <img width="100px" height="100px" src="' .$prizeImgUrl . '">
                            </a>';
                });
                $grid->column('view_prize_img', '查看奖项图片')->width(140)->display(function () {
                    if ($this->prize_type == ToC::PRIZE_TYPE_LOSE) {
                        return '';
                    }
                    $prizeImgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $this->view_prize_img, ImgUrl::IMAGE_SIZE_SQ_PHONE);
                    return '<a href="' . $prizeImgUrl . '" target="_blank">
                                <img width="100px" height="100px" src="' .$prizeImgUrl . '">
                            </a>';
                });
                $grid->column('left_sku_num', '剩余库存')->editable();
                $grid->column('yesterday_reduce', '昨日消耗');
                $grid->column('today_reduce', '当日消耗');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
//                    $actions->disableEdit();
                });
            }
        );
        return $content
            ->header('TOC活动奖品列表')
            ->row($gridList);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        if ($id) {
            $data = ToCPrize::get('*', ['id' => $id]);
            $data['sku_num'] = cDcToC::getPrizeSkuNum($id);
            $form = new Form($data);
        } else {
            $form = new Form([]);
        }
        if (!empty($id)) {
            $form->text('id', 'ID')->readOnly();
        }
        $form->text('name', '奖项名称')->required();
        $form->text('full_name', '奖项全称')->required();
        $form->select('prize_type', '奖项类别')
            ->options(ToC::PRIZE_TYPE_TXT)
            ->default(ToC::PRIZE_TYPE_LOSE)
            ->required();
        $form->text('sku_num', '当日库存')->required()
            ->help('当为未中奖时，该值为未中奖概率，即抽中"谢谢参与"的概率');
        $form->imgUpload('play_prize_img', '转盘奖项图片', false,
            [
                'imgType' => ImgUrl::APPTYPE_APP,
                'imgSize' => ImgUrl::IMAGE_SIZE_SQ_PHONE
            ]);
        $form->imgUpload('win_prize_img', '得奖奖项图片', false,
            [
                'imgType' => ImgUrl::APPTYPE_APP,
                'imgSize' => ImgUrl::IMAGE_SIZE_SQ_PHONE
            ]);
        $form->imgUpload('view_prize_img', '奖项图片', false,
            [
                'imgType' => ImgUrl::APPTYPE_APP,
                'imgSize' => ImgUrl::IMAGE_SIZE_SQ_PHONE
            ]);
        $form->confirm('确定提交吗？');
        $form->action('/admin/DesignerCompetition2021/toc/prize/save');

        $header = '信息修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '奖项列表'],
                ['text' => '编辑奖项信息'],
            )->row($tab);
    }

    // 编辑奖项
    public function save(Request $request) {
        $request = $request->all();
        if ($request['prize_type'] == ToC::PRIZE_TYPE_WIN) {
            if (empty($request['play_prize_img']) || empty($request['win_prize_img']) || empty($request['view_prize_img'])) {
                $error = new MessageBag(['title' => '图片必传']);
                return back()->with(compact('error'));
            }
        }
        $data = [
            'name' => $request['name'],
            'full_name' => $request['full_name'],
            'prize_type' => $request['prize_type'],
            'sku_num' => $request['sku_num'],
            'play_prize_img' => $request['play_prize_img'],
            'win_prize_img' => $request['win_prize_img'],
            'view_prize_img' => $request['view_prize_img'],
        ];
        if (isset($request['id'])) {
            $rs = ToCPrize::updateInfo($data, ['id' => $request['id']]);
            $prizeId = $request['id'];
        } else {
            if (ToCPrize::get('*', ['name' => $request['name']])) {
                $error = new MessageBag(['title' => '已经存在该奖项']);
                return back()->with(compact('error'));
            }
            $prizeId = $rs = ToCPrize::addInfo($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if ($rs === false) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        cDcToC::setPrizeSkuNum($prizeId, $data['sku_num']);
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/DesignerCompetition2021/toc/prize')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $prize = ToCPrize::get('*', ['id' => $id]);
        if ($prize) {
            if (ToCPrize::delete(['id' => $id]) === false) {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
            cDcToC::removePrizeSkuNum($id);
        } else {
            return response()->json([
                'status' => false,
                'message' => "该评审不存在",
            ]);
        }
    }

    public function saveSkuNum(Request $request, $id) {
        $skuNum = $request->input('value');
        if (!ToCPrize::updateInfo(['sku_num' => $skuNum], ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        cDcToC::setPrizeSkuNum($id, $skuNum);
        return response()->json([
            'status' => true,
        ]);
    }

    public function formatList(&$list) {
        foreach ($list as &$item) {
            $leftSkuNum = cDcToC::getPrizeSkuNum($item['id']);
            $item['left_sku_num'] = $leftSkuNum <= 0 ? 0 : $leftSkuNum;
            $item['yesterday_reduce'] = $item['prize_type'] != ToC::PRIZE_TYPE_LOSE ? ToCActionLog::count([
                'action_type' => ToC::ACTION_TYPE_PLAY,
                'assoc_id' => $item['id'],
                'add_time[>=]' => strtotime(date("Y-m-d",strtotime("-1 day"))." 00:00:00"),
                'add_time[<=]' => strtotime(date("Y-m-d",strtotime("-1 day"))." 24:00:00")
            ]) : '';
            $item['today_reduce'] = $item['prize_type'] != ToC::PRIZE_TYPE_LOSE ? ToCActionLog::count([
                'action_type' => ToC::ACTION_TYPE_PLAY,
                'assoc_id' => $item['id'],
                'add_time[>=]' => strtotime(date('Y-m-d 00:00:00')),
                'add_time[<=]' => strtotime(date('Y-m-d 24:00:00'))
            ]) : '';
        }
    }
}
